package com.example.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.*;

public class Receiver {

    public static void main(String[] args) {
        DatagramSocket socket = null;
        try {
            //1. 开放udp协议下的端口
            socket = new DatagramSocket(9090);
            //2. 接收数据包
            byte[] buffer = new byte[64];
            DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
            //3. 阻塞接收
            while(true){
                socket.receive(packet);
                String[] temp = new String(buffer).split(" ");
                assert temp.length == 2;
                double highTemp = Double.parseDouble(temp[0]);
                double lowTemp = Double.parseDouble(temp[1]);
                System.out.printf("接收到温度：最高温：%.3f 最低温：%.3f%n", highTemp, lowTemp);
                // 向服务器发送post请求
                JSONObject param = new JSONObject();
                param.put("highTemp", highTemp);
                param.put("lowTemp", lowTemp);
                HttpPost httpPost = new HttpPost("http://localhost:8080/line/temperature");
                CloseableHttpClient client = HttpClients.createDefault();
                //请求参数转JOSN字符串
                StringEntity entity = new StringEntity(param.toString(), "UTF-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
                try {
                    HttpResponse response = client.execute(httpPost);
                    if (response.getStatusLine().getStatusCode() == 200) {
                        System.out.println("消息发送成功");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            //4. 关闭连接
            if(null != socket){
                socket.close();
            }
        }

    }
}
